package com.mall.product.controller;

import com.mall.common.utils.PageResult;
import com.mall.common.utils.Result;
import com.mall.common.valid.AddGroup;
import com.mall.common.valid.UpdateGroup;
import com.mall.common.valid.UpdateStatusGroup;
import com.mall.product.entity.BrandEntity;
import com.mall.product.service.BrandService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Autowired
    private BrandService brandService;


    @GetMapping("/page")
    public Result page(int current, int size, Long brandId, String name, String firstLetter) {
        PageResult<BrandEntity> page = brandService.page(current, size, brandId, name, firstLetter);

        return Result.ok().put("data", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public Result list() {
        return Result.ok().put("page", brandService.list());
    }


    /**
     * 根据id查询
     */
    @GetMapping("/getBrandId")
    public Result getBrandId(@Param("brandId") Long brandId) {
        BrandEntity brand = brandService.getById(brandId);

        return Result.ok().put("data", brand);
    }

    /**
     * 保存
     */
    //, BindingResult bindingResult
    @PostMapping("/save")
    public Result save(@RequestBody @Validated(value = {AddGroup.class}) BrandEntity brand) {
//        if (bindingResult.hasErrors()) {
//            Map<String, String> map = new HashMap<>();
//            //1、获取校验的错误结果
//            bindingResult.getFieldErrors().forEach((item) -> {
//                //FieldError 获取到错误提示
//                String message = item.getDefaultMessage();
//                //获取错误的属性的名字
//                String field = item.getField();
//                map.put(field, message);
//            });
//            return Result.error(400, "提交的数据不合法").put("data", map);
//        }

        brandService.save(brand);

        return Result.ok();
    }

    /**
     * 修改
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated(value = {UpdateGroup.class}) BrandEntity brand) {
        brandService.updateById(brand);

        return Result.ok();
    }

    /**
     * 修改状态
     */
    @PutMapping("/update/status")
    public Result updateStatus(@RequestBody @Validated(value = {UpdateStatusGroup.class}) BrandEntity brand) {
        brandService.updateById(brand);

        return Result.ok();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public Result delete(@RequestBody List<Long> ids) {
        brandService.removeByIds(ids);

        return Result.ok();
    }

}
